import axios from "axios";
import {getRedirectPath} from "../utils";

const ERR_MSG = "ERR_MSG";
const AUTH_SUCCESS = "AUTH_SUCCESS";
const LOAD_DATA = "LOAD_DATA";
const LOGO_OUT = "LOGO_OUT";

const initState = {
  redirectTo: "",
  username: "",
  role: "",
  msg: ""
};

/*
* 用户信息
* */
export function user (state = initState, action) {
  switch (action.type) {
    case  AUTH_SUCCESS:
      return {
        ...state,
        redirectTo: getRedirectPath(action.payload),
        ...filterPwdData(action.payload)
      };
    case LOAD_DATA:
      return {...state, isAuth: true, ...action.payload};
    case LOGO_OUT:
      return {...initState, redirectTo: "/login"};
    case ERR_MSG:
      return {...state, isAuth: false, msg: action.msg};
    default:
      return state;
  }
}

/*
* 过滤密码
* */
function filterPwdData (obj) {
  const {pwd, ...data} = {...obj};
  return data;
}

/*
* 退出
* */

export function logout () {
  return {type: LOGO_OUT, payload: {}};
}

/*
* 刷新加载数据
* */
export function loadData (data) {
  return {type: LOAD_DATA, payload: data};
}

/*
* 登录
* */

export function login ({username, pwd}) {
  if (!username || !pwd) {
    return errMsg("用户名或密码不能为空");
  }
  return dispatch => {
    axios.post("/user/login", {username, pwd})
      .then(res => {
        if (res.status === 200 && res.data.code === 0) {
          dispatch({
            type: AUTH_SUCCESS,
            payload: res.data.data
          });
        } else {
          dispatch(errMsg("登录失败,请稍后再试!"));
        }
      })
      .catch(e => {
        dispatch(errMsg(e.toString()));
      });
  };
}


/*
* 注册
* */
export function register ({username, pwd, repeat_pwd, role}) {
  if (!username || !pwd || !role) {
    return errMsg("用户名或密码不能为空!");
  }
  if (pwd !== repeat_pwd) {
    return errMsg("密码和确认密码必须一致!");
  }
  return dispatch => {
    axios.post("/user/register", {username, pwd, repeat_pwd, role})
      .then(res => {
        if (res.status === 200 && res.data.code === 0) {
          dispatch({
            type: AUTH_SUCCESS,
            payload: res.data.data
          });
        } else {
          dispatch(errMsg(res.data.msg));
        }
      })
      .catch(e => {
        dispatch(errMsg(e.toString()));
      });
  };

}


/*
* 更新用户信息
* */
export function update (data) {
  if (!data) {
    return errMsg("更新的信息为空");
  }
  return dispatch => {
    axios.post("/user/update", data)
      .then(res => {
        if (res.status === 200 && res.data.code === 0) {
          dispatch({
            type: AUTH_SUCCESS,
            payload: res.data.data
          });
        } else {
          dispatch(errMsg(res.data.msg));
        }
      })
      .catch(err => {
        dispatch(errMsg(err.toString()));
      });
  };
}


function errMsg (msg) {
  return {
    msg,
    type: ERR_MSG
  };
}



